package gov.fema.hazus.bdc.server.servlet.tasks;

import gov.fema.hazus.bdc.server.servlet.DAO;
import gov.fema.hazus.bdc.shared.entity.Address;
import gov.fema.hazus.bdc.shared.entity.Building;
import gov.fema.hazus.bdc.shared.entity.Location;

import java.io.IOException;
import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.api.labs.taskqueue.TaskOptions;
import com.google.appengine.api.labs.taskqueue.TaskOptions.Method;
import com.google.inject.Singleton;
import com.googlecode.objectify.OQuery;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

@Singleton
public class TaskQueueDeleteBuildingsObjectify extends HttpServlet {

	public static final String TASK_PATH = "/task/objectify/buildings/delete";

	private static final long serialVersionUID = -6324912257245810139L;
	private final Logger logger = Logger.getLogger(TaskQueueDeleteBuildingsObjectify.class);
    private Cache cache;

    private DAO dao = new DAO();
    
    public void init(ServletConfig config) throws ServletException {

        // Store the ServletConfig object and log the initialization
        super.init(config);
        logger.debug("Initializing servlet");
        
       try {
        	logger.debug("Initializing cache");
        	cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
            logger.debug("Could not setup cache");
        }
        
    }
    
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	 throws ServletException, IOException {
		
		
		String idString = req.getParameter("id");
		Long id = Long.parseLong(idString);
		logger.debug("Parse id:" + id);
		
		try {
			
			Building building = dao.ofy().get(Building.class, id);
			Address address = dao.ofy().get(Address.class, id);
			Location location = dao.ofy().get(Location.class, id);
			
			dao.ofy().delete(building);
			dao.ofy().delete(address);
			dao.ofy().delete(location);
			
			
		} catch (EntityNotFoundException e) {
			e.printStackTrace();
		}
		
		
		
		
	 }
	
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws IOException {
        
    	res.setContentType("text/plain");

    	res.getWriter().println("Deleting all buildings with all child entities");

    	Objectify ofy = ObjectifyService.begin();
		OQuery<Building> q = ObjectifyService.createQuery(Building.class);
		for (Building building: ofy.prepare(q).asIterable()) {
			String taskNotice = "Creating a delete task for row("+building.getId()+")";
    		res.getWriter().println(taskNotice);
    		logger.debug(taskNotice);
    		Queue queue = QueueFactory.getQueue("delete-buildings");
    		queue.add(TaskOptions.Builder.url(TASK_PATH).method(Method.POST).param("id",Long.toString(building.getId())));
		}
    	
    }
    
}
